<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;

// 权限组model类
use app\model\Auth as AuthModel;
// 目录控制model类
use app\model\Menu as MenuModel;
// 获取完整权限目录
use app\service\Menu as MenuService;

class Auth extends Base
{
    /**
     * 查询权限组列表
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function index(Request $request)
    {
        $params = request()->rsa_data;
        // 获取数据区域
        $page = $params['page'] ? intval($params['page']) : 1;
        $size = $params['size'] ? intval($params['size']) : 10;
        
        $list = AuthModel::page($page,$size);
        $data = [
            // 总条数
            'total' => $list->count(),
            // 查询指定数据
            'list'  => $list->select()->toArray(),
            // 页码
            'page'  => $page,
        ];
        return $this->createMsg($data, '查询成功!', 200);
    }
    
    /**
     * 新增权限组
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function add(Request $request)
    {
        $params = request()->rsa_data;
        if($params['name']){
            $newAuth = AuthModel::create([
                // 名称
                'permission_name'  =>  $params['name'],
            ]);
            return $this->createMsg([], '新增成功!', 200);
        }else{
            return $this->createMsg([], '名称是必须的!', 400);
        }
    }
    
    /**
     * 查看权限组所拥有的权限
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function view(Request $request)
    {
        $params = request()->rsa_data;
        // 查询指定用户的权限
        $idsData = AuthModel::field('permission_ids')->where('id',$params['id'])->find();
        $ids = [];
        if($idsData['permission_ids']){
            // 将字符串存储的id切换成数组保存
            $ids = explode(',', $idsData['permission_ids']);
        }
        // 获取完整倒焊列表
        $MenuService = new MenuService();
        $list = $MenuService->getMenuList();
        
        return $this->createMsg(['ids'=>$ids,'list'=>$list], '查询成功!', 200);
    }
    
    /**
     * 修改权限组所拥有的权限
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function edit(Request $request)
    {
        $params = request()->rsa_data;
        
        // 查询指定用户的权限
        $data = AuthModel::where('id',$params['id'])->find();
        $data->permission_ids = $params['ids'];
        if($data->save()){
            return $this->createMsg([], '修改完成!', 200);
        }else{ 
            return $this->createMsg([], '修改失败!', 400);
        }
        return $this->createMsg(['ids'=>$ids,'list'=>$list], '修改成功!', 200);
    }
    
}